#include "main.h"
#include "func_system.h"
#include "func_led.h"
#include "cmsis_os.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

void led_TaskFunction(void *pvParameters)
{
  portBASE_TYPE rec;
  LEDQueueDataType data;
  LEDBLINK_TYPE led[2];
  LEDTaskParaTypeDef* para = pvParameters;
  SystemInfoTypeDef sysinfo;
  sysinfo = sysinfo_Read();
  led[0].gpio = para->signal_gpio[0];
  led[0].pin = para->signal_pin[0];
  led[1].gpio = para->signal_gpio[1];
  led[1].pin = para->signal_pin[1];
  if(sysinfo.config.devicetype == TYPE_startDummy)
    led[0].mode = LED_ON;
  else
    led[0].mode = LED_OFF;
  led[1].mode = LED_OFF;
  led[0].tick = led[1].tick = 0;
  led[0].timeout = led[1].timeout = 0;
  HAL_GPIO_WritePin(para->signal_gpio[0],para->signal_pin[0],GPIO_PIN_SET);
  vTaskDelay(2000/portTICK_RATE_MS);
  while(1)
  {
    rec = xQueueReceive(led_queue,&data,10);
    if(rec)
    {
      switch(data)
      {
      case LED_MissionStart:
        if(sys.config.devicetype == TYPE_startDummy)
          led[0].mode = LED_OFF;
        else
          led[0].mode = LED_ON;
        break;
      case LED_MissionStop:
        if(sys.config.devicetype == TYPE_startDummy)
          led[0].mode = LED_ON;
        else
          led[0].mode = LED_OFF;
        break; 
      case LED_Hit:
        led[0].mode = LED_FAST_ON;
        led[0].timeout = 10;
        break;
      }
      led[0].tick = 0;
    }
    LEDBlink_handler(&led[0]);
    LEDBlink_handler(&led[1]);
    vTaskDelay(250/portTICK_RATE_MS);
  }
  vTaskDelete(NULL);
}

void LEDBlink_handler(LEDBLINK_TYPE* led)
{
  switch(led->mode)
  {
  case LED_OFF:
    led->tick = 0;
    HAL_GPIO_WritePin(led->gpio,led->pin,GPIO_PIN_RESET);
    break;
  case LED_ON:
    led->tick = 0;
    HAL_GPIO_WritePin(led->gpio,led->pin,GPIO_PIN_SET);
    break;
  case LED_SLOW:
    if(led->tick == 0)
      HAL_GPIO_TogglePin(led->gpio,led->pin);
    led->tick++;
    if(led->tick>5)
      led->tick = 0;
    break;
  case LED_FAST_ON:
    led->timeout--;
    if(led->timeout == 0)
      led->mode = LED_OFF;
  case LED_FAST:
    led->tick = 0;
    HAL_GPIO_TogglePin(led->gpio,led->pin);
    break;
  default:
    led->mode = LED_OFF;
  }
}